<?php
/**
 * 单页
 */
namespace App\Service;

use App\Models\EwMember;
use App\Models\EwUser;
use App\Models\EwLogin3;
use App\Models\EwMemberAuth;

use Phalcon\Mvc\Model\Transaction\Failed as TxFailed;
use Phalcon\Mvc\Model\Transaction\Manager as TxManager;
use App\Models\EwRoles;
class UserService  extends BaseService
{
	const STATA_TRUE = 2;		//1禁用，2正常
	const STATA_FALSE = 1;		//1禁用，2正常
	const AUTH_ING = 1;			//1认证中,2通过,3拒绝
	const AUTH_PASS = 2;		//1认证中,2通过,3拒绝
	const AUTH_DENY = 3;		//1认证中,2通过,3拒绝
	const DEL_TRUE = 1;			//删除标识：是
	const DEL_FALSE = 0;		//删除标识：否

	public static function getList($params, $count = FALSE)
	{
		// var_dump($params);die;
		$builder = new \Phalcon\Mvc\Model\Query\Builder();
		if (isset($params->role_id) && $params->role_id == 2){ //1会员2管理员
			$builder->columns(['u.id,u.account,u.ip,u.role_id,r.role_name,u.mobile,u.last_login_time,u.create_time']);

		}else{
			$builder->columns(['u.id,u.account,u.ip,u.role_id,r.role_name,u.mobile,u.last_login_time,u.create_time,m.nickname,m.bg_image,m.avatar,m.sex,m.sign,m.address,m.auth_state,m.state,m.is_del']);
			$builder->andWhere("m.is_del = " . self::DEL_FALSE);
		}
		$builder->addFrom("App\Models\EwUser", 'u');
		$builder->leftJoin("App\Models\EwMember", 'u.id = m.id' , 'm');
		$builder->leftJoin("App\Models\EwRoles", 'u.role_id = r.id' , 'r');
        $builder->orderBy(" u.id desc");
		//role_id
		if (isset($params->role_id) && $params->role_id)
			$builder->andWhere("u.role_id >1 " );//查询系统管理员

		if ($count)
			return $builder->getQuery()->execute()->count();

		$builder->limit($params->page_num,($params->p-1)*$params->page_num);
		$result = $builder->getQuery();

		return $result->execute();
	}

	public static function getInfo($id = 0)
	{
		return EwMember::findFirst($id);
	}

	/**
	 * [getInfo 获取会员详情]
	 * @param  integer $id [description]
	 * @return [type]      [description]
	 */
	public static function getUserInfo($id = 0)
	{
		$builder = new \Phalcon\Mvc\Model\Query\Builder();
		$builder->columns(['u.id,u.account,u.ip,u.role_id,r.role_name,u.mobile,u.last_login_time,u.create_time,m.nickname,m.bg_image,m.avatar,m.sex,m.sign,m.address,m.auth_state,m.state,m.is_del']);
		$builder->addFrom("App\Models\EwUser", 'u');
		$builder->leftJoin("App\Models\EwMember", 'u.id = m.id' , 'm');
		$builder->leftJoin("App\Models\EwRoles", 'u.role_id = r.id' , 'r');
		$builder->andWhere("u.id = " . $id);
		$builder->andWhere("u.role_id = 1");
		$result = $builder->getQuery()->execute()->toArray();

		$data = new \stdClass();
		if (is_array($result) && isset($result[0]) && is_array($result[0])){
			foreach ($result[0] as $key => $value) {
				$data->$key = $value;
			}
		}
		return $data;

	}

	/**
	 * [getAdminInfo 获取管理员详情]
	 * @param  integer $id [description]
	 * @return [type]      [description]
	 */
	public static function getAdminInfo($id = 0)
	{
		$builder = new \Phalcon\Mvc\Model\Query\Builder();
		$builder->columns(['u.id,u.account,u.ip,u.role_id,r.role_name,u.mobile,u.last_login_time,u.create_time']);
		$builder->addFrom("App\Models\EwUser", 'u');
		$builder->leftJoin("App\Models\EwRoles", 'u.role_id = r.id' , 'r');
		$builder->andWhere("u.id = " . $id);
		$builder->andWhere("u.role_id = 2 ");
		$result = $builder->getQuery()->execute()->toArray();

		$data = new \stdClass();
		if (is_array($result) && isset($result[0]) && is_array($result[0])){
			foreach ($result[0] as $key => $value) {
				$data->$key = $value;
			}
		}
		return $data;
	}

	//通过手机号
	public static function getMobileInfo($mobile)
	{
		$user = new \stdClass();
		$u = EwUser::findFirst([
			"mobile = :mobile:",
			"bind" => [
				"mobile" => $mobile,
			],
		]);

		if(empty($u->id)){
			$u = new EwUser();
			$u->account = $mobile;
			$u->mobile = $mobile;
			$u->save();
			$m = new EwMember();
			$m->id = $u->id;
			$m->save();

		}

		if($u->id){
			//事务开启
			// $member = EwMember::findFirst($u->id);
			// $user->member_id = $u->id;
			// $user->mobile = $u->mobile ? $u->mobile : "";
			// $user->nickname = $member->nickname ? $member->nickname : "";
			// $user->avatar = $member->avatar ? $member->avatar : "";
			// $user->role_id = $u->role_id;
			$member = EwMember::findFirst($u->id);
			$user->nickname =  NULL;
			$user->avatar = NULL;
			if ($member){
				$user->nickname = $member->nickname ? $member->nickname : "";
				$user->avatar = $member->avatar ? $member->avatar : "";
			}
			$user->member_id = $u->id;
			$user->account = $u->account ? $u->account : "";
			$user->mobile = $u->mobile ? $u->mobile : "";
			$user->role_id = $u->role_id;
		}

		return $user;

	}

	public static function getAccount($params)
	{
		return EwUser::findFirst([
			"account = :account:",
			"bind" => [
				"account" => $params->account,
			],
		]);
	}

	public static function getAccountInfo($params)
	{
		$user = new \stdClass();
		$u = EwUser::findFirst([
			"account = :account: AND pwd = :pwd:",
			"bind" => [
				"account" => $params->account,
				"pwd"	=> md5(md5($params->pwd).md5($params->pwd))
			],
		]);

		if (empty($u->id)){
			return NULL;
		}

		if ($u->id){
			$member = EwMember::findFirst($u->id);
			$user->nickname =  NULL;
			$user->avatar = NULL;
			if ($member){
				$user->nickname = $member->nickname ? $member->nickname : "";
				$user->avatar = $member->avatar ? $member->avatar : "";
			}
			$user->member_id = $u->id;
			$user->account = $u->account ? $u->account : "";
			$user->mobile = $u->mobile ? $u->mobile : "";
			$user->role_id = $u->role_id;
            $user->roles_info = EwRoles::findFirst($user->role_id);
		}

		return $user;
	}

	public static function count()
	{
		return EwMember::count();
	}

	public static function save($data){
		$row = EwMember::findFirst($data->member_id);
		if($row && $row->avatar){
			unset($data->avatar);
		}
		return $row->save((array)$data);

	}

	/**
	 * [addUser 添加用户]
	 * @param [type] $data [description]
	 */
	public static function addUser($data)
	{
		$user = new EwUser;
	  	$user->save();

		$member = new EwMember;
		$member->id = $user->id;
		$member->nickname = property_exists($data,'nickname') ? $data->nickname : $data->account;
		$member->avatar = property_exists($data,'avatar') ? $data->avatar : '';
		$member->sex = property_exists($data,'sex') ? $data->sex : 0;
		$member->save();

		$user->account = $data->account;
		$user->pwd = $data->pwd;
		$user->last_login_time = $data->last_login_time;
		$user->creator_id = $data->creator_id;
		$user->save();

		return $user->id;
	}

	//
	public static function getLogin3Info($open_id){
		$user = new \stdClass();
		$login3 = EwLogin3::findFirstByOpenId($open_id);
		if(!empty($login3->id)){
			$member = EwMember::findFirst($login3->member_id);
			$u = EwUser::findFirst($login3->member_id);
			$user->member_id = $login3->member_id;
			$user->mobile = $u->mobile ? $u->mobile : "";
			$user->nickname = $member->nickname ? $member->nickname : "";
			$user->avatar = $member->avatar ? $member->avatar : "";
			$user->role_id = $u->role_id;
		}
		return $user;
	}

	//第三方登录记录
	public static function login3Save($data){

			$user = new EwUser;
		  $user->save();

		  $member = new EwMember;
		  $member->id = $user->id;
		  $member->nickname = $data->nickname;
		  $member->avatar = $data->avatar;
		  $member->save();

			$login3 = new EwLogin3;
			$login3->member_id = $user->id;
			$login3->open_id = $data->open_id;
			$login3->login_type = $data->origin;
			$login3->save();

			return $user->id;
	}

	/**
	 * [on 启用]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function on($id)
	{
		if (isset($id) && $id)
			$data = EwMember::findFirst($id);

		if ($data){
			$data->state = self::STATA_TRUE;
			return $data->save();
		}

		return NULL;
	}

	/**
	 * [off 禁用]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function off($id)
	{
		if (isset($id) && $id)
			$data = EwMember::findFirst($id);

		if ($data){
			$data->state = self::STATA_FALSE;
			return $data->save();
		}

		return NULL;
	}

	/**
	 * [delete 移除数据]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function delete($id)
	{
		if (isset($id) && $id)
			$data = EwMember::findFirst($id);

		if ($data){
			$data->is_del = self::DEL_TRUE;
			return $data->save();
		}

		return NULL;
	}

	/**
	 * [restore 恢复数据]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function restore($id)
	{
		if (isset($id) && $id)
			$data = EwMember::findFirst($id);

		if ($data){
			$data->is_del = self::DEL_FALSE;
			return $data->save();
		}

		return NULL;
	}


	/**
	 * [delete 彻底删除数据]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function forever($id)
	{
		return FALSE;
		//事务
        try {
		    // Create a transaction manager
		    $manager = new TxManager();

		    // Request a transaction
		    $transaction = $manager->get();

		    $auth = EwMemberAuth::findFirst($id);
		    $auth->setTransaction($transaction);
		    if ($auth->delete() === FALSE) {
		        $transaction->rollback(
		            "Cannot delete auth"
		        );
		    }

		    $member = EwMember::findFirst($id);
		    $member->setTransaction($transaction);
		    if ($member->delete() === FALSE) {
		        $transaction->rollback(
		            "Cannot delete member"
		        );
		    }

		    $user = EwUser::findFirst($id);
		    $user->setTransaction($transaction);
		    if ($user->delete() === FALSE) {
		        $transaction->rollback(
		            "Cannot delete user"
		        );
		    }

		    // Everything's gone fine, let's commit the transaction
		    $transaction->commit();
		} catch (TxFailed $e) {
		    echo "Failed, reason: ", $e->getMessage();
		}

    }
    //录记录
    public static function createBackUser($data){
        $user = new EwUser;
        $user->save($data);
        return $user->id;
    }
    public static function updatePwd($data){


        $row = EwUser::findFirst($data["id"]);

        return $row->save($data);

    }
}